<template>
  <div class="user-management">
    <div class="page-header">
      <h2>用户管理</h2>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        添加用户
      </el-button>
    </div>

    <!-- 搜索筛选 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="用户名">
          <el-input 
            v-model="searchForm.username" 
            placeholder="请输入用户名"
            clearable
          />
        </el-form-item>
        <el-form-item label="真实姓名">
          <el-input 
            v-model="searchForm.realName" 
            placeholder="请输入真实姓名"
            clearable
          />
        </el-form-item>
        <el-form-item label="角色">
          <el-select 
            v-model="searchForm.role" 
            placeholder="请选择角色"
            clearable
          >
            <el-option label="管理员" value="ADMIN" />
            <el-option label="教师" value="TEACHER" />
            <el-option label="学生" value="STUDENT" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select 
            v-model="searchForm.enabled" 
            placeholder="请选择状态"
            clearable
          >
            <el-option label="启用" :value="true" />
            <el-option label="禁用" :value="false" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table 
        :data="tableData" 
        :loading="loading"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="realName" label="真实姓名" width="120" />
        <el-table-column prop="email" label="邮箱" width="180" />
        <el-table-column prop="phone" label="手机号" width="120" />
        <el-table-column prop="department" label="院系" width="150" />
        <el-table-column prop="roles" label="角色" width="150">
          <template #default="{ row }">
            <el-tag 
              v-for="role in row.roles" 
              :key="role.roleName"
              :type="getRoleType(role.roleName)"
              size="small"
              style="margin-right: 4px;"
            >
              {{ getRoleText(role.roleName) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="enabled" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.enabled ? 'success' : 'danger'">
              {{ row.enabled ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="150">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="text" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button 
              type="text" 
              @click="handleToggleStatus(row)"
              :style="{ color: row.enabled ? '#f56c6c' : '#67c23a' }"
            >
              {{ row.enabled ? '禁用' : '启用' }}
            </el-button>
            <el-button 
              type="text" 
              @click="handleResetPassword(row)"
              style="color: #e6a23c"
            >
              重置密码
            </el-button>
            <el-button 
              type="text" 
              @click="handleDelete(row)"
              style="color: #f56c6c"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 用户表单对话框 -->
    <el-dialog 
      v-model="formDialogVisible" 
      :title="isEdit ? '编辑用户' : '添加用户'" 
      width="600px"
    >
      <el-form 
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input 
                v-model="form.username" 
                placeholder="请输入用户名"
                :disabled="isEdit"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="真实姓名" prop="realName">
              <el-input 
                v-model="form.realName" 
                placeholder="请输入真实姓名"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20" v-if="!isEdit">
          <el-col :span="12">
            <el-form-item label="密码" prop="password">
              <el-input 
                v-model="form.password" 
                type="password"
                placeholder="请输入密码"
                show-password
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input 
                v-model="form.confirmPassword" 
                type="password"
                placeholder="请再次输入密码"
                show-password
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input 
                v-model="form.email" 
                placeholder="请输入邮箱"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input 
                v-model="form.phone" 
                placeholder="请输入手机号"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="学号/工号" prop="studentId">
              <el-input 
                v-model="form.studentId" 
                placeholder="请输入学号或工号"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="院系" prop="department">
              <el-input 
                v-model="form.department" 
                placeholder="请输入院系"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="专业" prop="major">
              <el-input 
                v-model="form.major" 
                placeholder="请输入专业"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="年级" prop="grade">
              <el-input 
                v-model="form.grade" 
                placeholder="请输入年级"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="角色" prop="roles">
          <el-checkbox-group v-model="form.roles">
            <el-checkbox label="ADMIN">管理员</el-checkbox>
            <el-checkbox label="TEACHER">教师</el-checkbox>
            <el-checkbox label="STUDENT">学生</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        
        <el-form-item label="状态" prop="enabled">
          <el-switch 
            v-model="form.enabled"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="formDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave" :loading="saving">
          保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh } from '@element-plus/icons-vue'
import { userAPI } from '@/api/user'

export default {
  name: 'UserManagement',
  components: {
    Plus,
    Search,
    Refresh
  },
  setup() {
    const loading = ref(false)
    const saving = ref(false)
    const tableData = ref([])
    const formDialogVisible = ref(false)
    const formRef = ref()
    const isEdit = ref(false)
    
    const searchForm = reactive({
      username: '',
      realName: '',
      role: '',
      enabled: null
    })
    
    const pagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: 0
    })
    
    const form = reactive({
      username: '',
      realName: '',
      password: '',
      confirmPassword: '',
      email: '',
      phone: '',
      studentId: '',
      department: '',
      major: '',
      grade: '',
      roles: [],
      enabled: true
    })
    
    const rules = reactive({
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' }
      ],
      realName: [
        { required: true, message: '请输入真实姓名', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, message: '请再次输入密码', trigger: 'blur' },
        {
          validator: (rule, value, callback) => {
            if (value !== form.password) {
              callback(new Error('两次输入的密码不一致'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }
      ],
      email: [
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
      ],
      roles: [
        { required: true, message: '请选择至少一个角色', trigger: 'change' }
      ]
    })
    
    // 编辑时不需要密码验证
    const editRules = computed(() => {
      const editRulesObj = { ...rules }
      delete editRulesObj.password
      delete editRulesObj.confirmPassword
      return editRulesObj
    })
    
    const loadData = async () => {
      loading.value = true
      try {
        const params = {
          page: pagination.currentPage - 1,
          size: pagination.pageSize,
          ...searchForm
        }
        
        const response = await userAPI.getAllUsers(params)
        tableData.value = response.data.content || []
        pagination.total = response.data.totalElements || 0
      } catch (error) {
        console.error('加载数据失败:', error)
        ElMessage.error('加载数据失败')
      } finally {
        loading.value = false
      }
    }
    
    const handleSearch = () => {
      pagination.currentPage = 1
      loadData()
    }
    
    const handleReset = () => {
      Object.keys(searchForm).forEach(key => {
        if (key === 'enabled') {
          searchForm[key] = null
        } else {
          searchForm[key] = ''
        }
      })
      pagination.currentPage = 1
      loadData()
    }
    
    const handleSizeChange = (size) => {
      pagination.pageSize = size
      loadData()
    }
    
    const handleCurrentChange = (page) => {
      pagination.currentPage = page
      loadData()
    }
    
    const handleAdd = () => {
      isEdit.value = false
      resetForm()
      formDialogVisible.value = true
    }
    
    const handleEdit = (row) => {
      isEdit.value = true
      Object.keys(form).forEach(key => {
        if (key === 'roles') {
          form[key] = row.roles ? row.roles.map(role => role.roleName) : []
        } else if (row[key] !== undefined) {
          form[key] = row[key]
        }
      })
      formDialogVisible.value = true
    }
    
    const handleSave = async () => {
      try {
        await formRef.value.validate()
        
        saving.value = true
        
        if (isEdit.value) {
          await userAPI.updateUser(form.id, form)
          ElMessage.success('更新成功')
        } else {
          await userAPI.createUser(form)
          ElMessage.success('创建成功')
        }
        
        formDialogVisible.value = false
        loadData()
      } catch (error) {
        console.error('保存失败:', error)
        ElMessage.error('保存失败')
      } finally {
        saving.value = false
      }
    }
    
    const handleToggleStatus = async (row) => {
      try {
        await userAPI.toggleUserStatus(row.id)
        ElMessage.success(row.enabled ? '禁用成功' : '启用成功')
        loadData()
      } catch (error) {
        console.error('状态切换失败:', error)
        ElMessage.error('状态切换失败')
      }
    }
    
    const handleResetPassword = async (row) => {
      try {
        await ElMessageBox.confirm('确定要重置该用户的密码吗？重置后密码为：password', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        await userAPI.changePassword(row.id, { newPassword: 'password' })
        ElMessage.success('密码重置成功')
      } catch (error) {
        if (error !== 'cancel') {
          console.error('重置密码失败:', error)
          ElMessage.error('重置密码失败')
        }
      }
    }
    
    const handleDelete = async (row) => {
      try {
        await ElMessageBox.confirm('确定要删除这个用户吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        await userAPI.deleteUser(row.id)
        ElMessage.success('删除成功')
        loadData()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败:', error)
          ElMessage.error('删除失败')
        }
      }
    }
    
    const resetForm = () => {
      Object.keys(form).forEach(key => {
        if (key === 'roles') {
          form[key] = []
        } else if (key === 'enabled') {
          form[key] = true
        } else {
          form[key] = ''
        }
      })
    }
    
    const getRoleText = (role) => {
      const roleMap = {
        ADMIN: '管理员',
        TEACHER: '教师',
        STUDENT: '学生'
      }
      return roleMap[role] || role
    }
    
    const getRoleType = (role) => {
      const typeMap = {
        ADMIN: 'danger',
        TEACHER: 'warning',
        STUDENT: 'success'
      }
      return typeMap[role] || 'info'
    }
    
    const formatDate = (date) => {
      if (!date) return '-'
      return new Date(date).toLocaleDateString('zh-CN')
    }
    
    onMounted(() => {
      loadData()
    })
    
    return {
      loading,
      saving,
      tableData,
      searchForm,
      pagination,
      formDialogVisible,
      formRef,
      isEdit,
      form,
      rules: computed(() => isEdit.value ? editRules.value : rules),
      loadData,
      handleSearch,
      handleReset,
      handleSizeChange,
      handleCurrentChange,
      handleAdd,
      handleEdit,
      handleSave,
      handleToggleStatus,
      handleResetPassword,
      handleDelete,
      getRoleText,
      getRoleType,
      formatDate
    }
  }
}
</script>

<style lang="scss" scoped>
.user-management {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h2 {
      margin: 0;
      color: #303133;
    }
  }
  
  .search-card {
    margin-bottom: 20px;
  }
  
  .table-card {
    .pagination-container {
      margin-top: 20px;
      text-align: right;
    }
  }
}
</style>
